#coding=utf-8
import re, logging, datetime, random
import wsgiref.handlers

from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.api.labs import taskqueue
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler

SERVERS = ['forum-email', 'forum-email4', 'forum-email2','forum-email3',]
URL = 'http://%s.appspot.com/get_email'
class GetMail(webapp.RequestHandler):
  def get(self):
    server = random.choice(SERVERS)
    url = URL%server
    #url = 'http://forum-email3.appspot.com/get_email'
    self.redirect(url)

class RejectedEmail(db.Model):
  addr = db.StringProperty(required=True)
  
  subject = db.StringProperty(multiline=True)
  content = db.TextProperty()
  
  rejected_at = db.DateTimeProperty(auto_now_add=True)
  flag = db.BooleanProperty(default=False)   
  
class Reject(webapp.RequestHandler):
  def post(self):
  
    email = self.request.get('email')
    sub = self.request.get('sub')
    content = self.request.get('content')
    
    RejectedEmail(addr=email, subject=sub, content=content).put()
    
    self.response.out.write(email)

class Deleter(webapp.RequestHandler):
  def get(self):
    model = self.request.get('model')
    #c = Counter(model)
      
    q = db.GqlQuery('select * from %s'%model)
    results = q.fetch(100)
    n = len(results)
    db.delete(results)
    #c.change_count(n)
    
    if n == 100:
      taskqueue.add(url='/delete', method='GET', params={'model': model})
      
class Query(webapp.RequestHandler):
  def get(self):
    addr = self.request.get('email')
    r = RejectedEmail.all().filter('addr =', addr).fetch(1)[0]
    self.response.out.write(addr)

class REFetcher(webapp.RequestHandler):
  def get(self):
    rs = RejectedEmail.all().fetch(10)
    if not rs:
      self.response.out.write('0')  
    for r in rs:
      self.response.out.write(r.addr)  
      self.response.out.write('<br/>')
    db.delete(rs)

class TestEmail(db.Model):
  sender = db.StringProperty(required=True)
  received_at = db.DateTimeProperty(auto_now_add=True)

class MailHandler(InboundMailHandler):
  def receive(self, message):
    _subject = message.subject
    _sender = message.sender
    bodies = message.bodies(content_type='text/plain')
    allBodies = "";
    for body in bodies:
        allBodies = allBodies + "\n---------------------------\n" + body[1].decode()  
    
    info = '发送者:%s\n标题:%s\n正文:%s\n'%(_sender, _subject, allBodies)
    logging.info(info)
    TestEmail(sender=_sender).put()
    
class Test(webapp.RequestHandler):
  def get(self):
    n = TestEmail.all().count()
    for te in TestEmail.all():
      db.delete(te)
    self.response.out.write('%i'%n)  

class Now(webapp.RequestHandler):
  def get(self):
    import datetime
    n = datetime.datetime.now()
    self.response.out.write(n)
    self.response.out.write('<br/>%i'%n.hour)
    
application = webapp.WSGIApplication([
  ('/get', GetMail),
  ('/reject', Reject),
  ('/delete', Deleter),
  ('/query', Query),
  ('/fetch_re', REFetcher),
  ('/test', Test),
  ('/now', Now),
  MailHandler.mapping(),
], debug=True)

def main():
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()
